package com.lax.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lax.bean.AdminBean;
import com.lax.result.GlobalHandleException;
import com.lax.result.ResponseResult;
import com.lax.result.ResultCode;
import com.lax.result.UserValid;
import com.lax.service.IAdminService;
import com.lax.util.JWTUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.http.HttpRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bdk
 * @since 2021-03-10
 */
@RestController
@RequestMapping("/admins")
public class AdminController {

    @Resource
    private IAdminService service;

    @ApiOperation("登录方法")
    @PostMapping("/login")
    @ResponseResult
    public Object login(String name, String pwd) throws GlobalHandleException {
        // 把用户输入的账号和密码封装到shiro框架提供的token对象中
        UsernamePasswordToken token = new UsernamePasswordToken(name, pwd);
        Subject currentUser = SecurityUtils.getSubject();
        try{
            //主体提交登录请求到SecurityManager
            currentUser.login(token);
        }catch(IncorrectCredentialsException ice){
            throw new GlobalHandleException(ResultCode.USER_PASS_ERROR);
        }catch (UnknownAccountException uae){
            throw new GlobalHandleException(ResultCode.USER_NOT_EXIST);
        }catch (AuthenticationException ae){
            throw new GlobalHandleException(ResultCode.USER_AUTHENTICATION_ERROR);
        }catch (AuthorizationException ae){
            throw new GlobalHandleException(ResultCode.USER_AUTHORIZATION_ERROR);
        }
        return currentUser.getPrincipal();
    }

    @PostMapping("/token")
    @UserValid
    @ResponseResult
    public Object getTokenUser() throws GlobalHandleException {
        AdminBean adminBean = (AdminBean) SecurityUtils.getSubject().getPrincipal();
        if(adminBean == null){
            throw new GlobalHandleException(ResultCode.USER_NOT_LOGGED_IN);
        }else {
            return adminBean;
        }

    }




    @GetMapping("/getZan")
    @ResponseResult
    public Object getZanInfo(int id){
        return service.findCommentZan(id);
    }


}

